<?

class Bootstrap
{		
	public function __construct($config)
	{
		//Error reporting, set level
		//error_reporting(E_ALL);
		error_reporting(0);
		
		//Memory settings
		ini_set('memory_limit', '1024M');
		
		//Set timeout limit
		set_time_limit(3600);
	
		//Globalize the root directory and hostname
		define('BASE_DIR', dirname(dirname(__FILE__)));
		define('HOST_NAME', 'http://' . $_SERVER['SERVER_ADDR']);
		
		//Setup the include path
		set_include_path(get_include_path() .
			PATH_SEPARATOR . BASE_DIR . '/library/' .
			PATH_SEPARATOR . BASE_DIR . '/library/Zend/library/' .
			PATH_SEPARATOR . BASE_DIR . '/application/controllers/' .
			PATH_SEPARATOR . BASE_DIR . '/application/models/' .
			PATH_SEPARATOR . BASE_DIR . '/application/forms/');

		//Register Zend_Loader to enable autoloading of classes
		include 'Zend/Loader/Autoloader.php';
		$autoloader = Zend_Loader_Autoloader::getInstance();
		$autoloader->setFallbackAutoloader(true);	
			
		//Identify as master, slave or hub (or all three)
		$config = new Zend_Config_Ini(BASE_DIR .
			'/application/config.ini', 'config');
		$hosts = new Zend_Config_Ini(BASE_DIR .
			'/application/config.ini', 'hosts');
		
		define('ROOT', $config->root);
		define('MASTER', $config->master);
		define('SLAVE', $config->slave);
		
		//Setup database connection
		$db = $this->setupDb('database');
		Zend_Registry::set('db', $db);

		//If we're a MASTER, add to ROOT table
		if(MASTER)
		{
			$root = new Root($hosts->root);
			
			$data = array(  'ip' 		=> HOST_NAME,
					'username'	=> $hosts->username,
					'password' 	=> $hosts->password);

			$root->register($data);
		}
		
		//If we're a SLAVE, add to MASTER table
		if(SLAVE)
		{
			$master = new Master($hosts->master);
			$data = array(	'ip' 		=> HOST_NAME,
							'username'	=> $hosts->username,
							'password' 	=> $hosts->password);
			$master->register($data);
		}
			
		//Create Dojo symlink
		if(! file_exists(BASE_DIR.'/public/js/dojo'))
			symlink(BASE_DIR.'/library/Zend/externals/dojo', 
				BASE_DIR.'/public/js/dojo');
	}
	
	public function runApp()
	{
		//Setup and dispatch Zend Front Controller
		Zend_Controller_Front::run(BASE_DIR.'/application/controllers');
	}
	
	private function setupDb()
	{
		$config = new Zend_Config_Ini(BASE_DIR.
			'/application/config.ini', 'database');
		
		$db = null;	
		try
		{
			$db = Zend_Db::factory($config->database);
			Zend_Db_Table_Abstract::setDefaultAdapter($db);
			Zend_Registry::set('db', $db);
		}
		catch(Exception $e)
		{	
			Logger::file()->err('Failed to connect with database');
		}
		return $db;
	}
}
